﻿using System;
using System.Linq;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Daemon.Stages;
using JetBrains.ReSharper.Daemon.Xml.Highlightings;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.Psi.Xml;
using JetBrains.ReSharper.Psi.Xml.Tree;
using SPCAFContrib.ReSharper.Common;
using SPCAFContrib.ReSharper.Common.Attributes;
using SPCAFContrib.ReSharper.Common.Extensions;
using SPCAFContrib.ReSharper.Common.XmlAnalysis;
using SPCAFContrib.ReSharper.Consts;
using SPCAFContrib.ReSharper.Inspection.Xml.SPCAF;

[assembly: RegisterConfigurableSeverity(SPC015205Highlighting.CheckId,
  null,
  Consts.SPCAF_CORRECTNESS_GROUP,
  SPC015205Highlighting.CheckId + ": " + SPC015205Highlighting.Message,
  "Length of attribute 'Name' in content types is limited to 124 characters or contains not allowed characters.",
  Severity.ERROR,
  false, Internal = false)]

namespace SPCAFContrib.ReSharper.Inspection.Xml.SPCAF
{
    [Applicability(
        IDEProjectType.SP2010FarmSolution |
        IDEProjectType.SPSandbox |
        IDEProjectType.SP2013FarmSolution)]
    public class DoNotDefineContentTypeNameWithMoreThan124Characters : XmlTagProblemAnalyzer
    {
        public override void Run(IXmlTag element, IHighlightingConsumer consumer)
        {
            if (element.GetProject().IsApplicableFor(this))
            {
                if (IsInvalid(element))
                {
                    SPC015205Highlighting errorHighlighting = new SPC015205Highlighting(element);
                    consumer.ConsumeHighlighting(element.Header.GetDocumentRange(), errorHighlighting);
                }
            }
        }

        public static bool IsInvalid(IXmlTag element)
        {
            bool result = false;

            if (element.Header.ContainerName == "ContentType" && element.AttributeExists("Name"))
            {
                string[] incorrectSymbols = {"\\","/", ":", "*", "?", "\"", "#", "%", "<", ">", "{", "}", "|", "~", "&", ",", ".." };

                string name = element.GetAttribute("Name").UnquotedValue;

                result = name.Length > 124 || incorrectSymbols.Any(s => name.Contains(s)); 
            }

            return result;
        }
    }

    [ConfigurableSeverityHighlighting(CheckId, XmlLanguage.Name, OverlapResolve = OverlapResolveKind.NONE, ShowToolTipInStatusBar = true)]
    public class SPC015205Highlighting : XmlErrorHighlighting
    {
        public const string CheckId = "SPC015205";
        public const string Message = "Do not define ContentType Name longer than 124 characters";

        public IXmlTag Element { get; private set; }

        public SPC015205Highlighting(IXmlTag element) :
            base(String.Format("{0}: {1}", CheckId, Message))
        {
            Element = element;
        }
    }
}
